
#include <stdio.h>   /* Standard input/output definitions */
#include <string.h>  /* String function definitions */
#include <unistd.h>  /* UNIX standard function definitions */
#include <fcntl.h>   /* File control definitions */
#include <errno.h>   /* Error number definitions */
#include <termios.h> /* POSIX terminal control definitions */
#include <stdio.h>
#include <unistd.h>

#define BAUDRATE B57600
#define SERPORT "/dev/ttyS0"

/*
 * 'open_port()' - Open serial port 1.
 *
 * Returns the file descriptor on success or -1 on error.
 */

/// Global variable
int fd; /* File descriptor for the port */

int open_port(void)
{
	fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY);

  	if (fd == -1)
 	{
		/* Could not open the port. */
 		perror(" open_port: Unable to open /dev/ttyS0 - ");
		printf(" Error with opening the port ! \n");
	}
  	else
	{
    		fcntl(fd, F_SETFL, 0);
		printf(" The port is opened! \n");
	}

	return (fd);
}


int options(void)
{
	// Read the configureation of the port
	struct termios options;
	
	/* SEt Baud Rate */

	cfsetispeed( &options, B57600 );
	cfsetospeed( &options, B57600 );
	printf(" Baud rate = 57600\n");
	   
	options.c_cflag &= ~PARENB;
	options.c_cflag &= ~CSIZE;
	options.c_cflag |= CS8;
	printf(" Bits = 8");

	options.c_iflag &= ~(IXON | IXOFF | IXANY);

	tcgetattr( fd, &options );
	return 0;
}
void SendToCreate( int fd, char *data, int length )
{
	int i;

	for( i=0; i<length; i++ )
	{
		if( write(fd, &data[i], 1) == -1 )
		{
  			printf( "\nUnable to write %s", SERPORT );
			printf( "\nerrno = %d", errno );
		}
		usleep( 5000 );
	}
	
}



int main(void)
{
char	data[256];

 

	printf("\n------------------------------------------------\n");
	printf("\n Program starts \n");

	open_port(); /// Open the port
	printf("\n************************************************\n Configureation of the port: \n\n");
	options();
	printf("\n************************************************\n  \n");
	
	data[0] = 128;
			data[1] = 136;
			data[2] = 1;
			data[3] = 0;
			data[4] = 0;
			data[5] = 0;
			data[6] = 0;
			SendToCreate( fd, data, 7 );

  	printf(" Start timer\n");
   	sleep(3);
   	printf(" Timer finished\n\n");

	data[0] = 128;
			data[1] = 131;
			data[2] = 0;
			data[3] = 0;
			data[4] = 0;
			data[5] = 0;
			data[6] = 0;
			SendToCreate( fd, data, 7 );
  	
	close(fd); /// It will close the port
	printf(" The port is closed \n");

	printf(" Program ends \n\n");
	printf("-------------------------------------------------\n\n");
	return 0;
}





